<?php
/**
 * お気に入り物件登録・削除API　モデルクラス<br />
 *
 * @package apamanshop
 * @author M.Matsutani
 * @copyright コピーライト(要確認)
 */
class Mypage_Model_Okiniiribukken extends Mypage_Model_Base
{
	/**
	 * お気に入り物件情報の登録
	 *
	 * @param $params
	 * @return エラーコード
	 */
	public function insertFavoriteBukken($params)
	{
		//DBパラメータ用配列生成
    	$db_params = array();

        $TorokuKbn = $params['TorokuKbn'];
        $resCd = "";

        //=====SQL生成=====
    //お気に入り物件登録(ﾏｲﾍﾟｰｼﾞ)
	If	($TorokuKbn == Apm_Config_Mypage::MYPAGE)
	{
        $sql = "";
        $sql .= "SELECT count(*) AS CNT FROM T99FAVORITE WHERE T99_USER_CD = '". $params['userCd'] . "' AND T99_HEYA_CD = '" . $params['heyaCd'] . "'";

        //=====データ取得=====
		$userDtl = $this->dbGetList($sql, $db_params);

		//重複チェック
		if ($userDtl[0]['CNT'] <> 0)
		  {
		  	$resCd = "9900";
		  }
		    else
		  {
		  	$sql = null;
		  	$sql .= "SELECT count(*) AS CNT FROM T99FAVORITE,T03WEB_HEYA WHERE T99_USER_CD = '". $params['userCd'] . "' AND T99_HEYA_CD = T03_HEYA_CD ";
		  	//=====データ取得=====
			$userDtl = $this->dbGetList($sql, $db_params);

			//登録件数チェック
			if ($userDtl[0]['CNT']>(Apm_Config_Mypage::CNT_MY_BUKKEN_MAX - 1))
			    {
			      $resCd = "9901";
			    }
			else
			    {
				  $db = $this->getDbConnection();
				  //トランザクション開始
				  $this->startTransaction($db);

			    try {
			    	$sql = "";
				  	$sql .= "INSERT INTO T99FAVORITE";
        		  	$sql .= "(";
		          	$sql .= "T99_USER_CD,";
		          	$sql .= "T99_HEYA_CD,";
		          	$sql .= "T99_TOUROKUBI,";
		          	$sql .= "T99_MYPAGE_KBN";
		          	$sql .= ")VALUES(";
		          	$sql .= "'" . $params['userCd'] . "',";
		          	$sql .= "'" . $params['heyaCd'] . "',";
		          	$sql .= "SYSDATE,";
		          	$sql .= "'1' )";

					//=====データ登録=====
					$this->dbExecQuery($sql, $db_params, $db,"T99FAVORITE");

					$this->commitTransaction($db);
					$resCd = "0000";

				} catch (Exception $e) {
					$this->rollbackTransaction($db);
					$resCd = "9902";
				}

				$db->closeConnection();

			    }
	  	  }
	}
	else
	{
        //お気に入り物件登録(ﾏｲﾍﾟｰｼﾞｸﾘｯﾌﾟ)
        $existFg = $params['ExistFg'];
        $listOver = $params['ListOver'];
		//重複時メッセージ表示用変数
		if ($existFg <> "" )
		{
			$resCd = "9900";
		//件数上限時メッセージ表示用変数
		}
		else If ($listOver <> "")
		{
			$resCd = "9901";
		}
		else
		{
			$resCd = "0000";
		}
	}
	return $resCd;
}

     /**
     * お気に入り物件削除
     *
     * @param String $UserCd ユーザCD, Array $strSeq_no 部屋CD
     * @return string $resCd エラーコード
     */
    public function deleteFavoriteBukken($UserCd, $strSeq_no)
    {
    	//DBパラメータ用配列生成
    	$db_params = array();

		$db = $this->getDbConnection();
		try
		{
			//トランザクション開始
		    $this->startTransaction($db);

			$db_params['user_cd'] = $UserCd;
		    $sql = "";
			$sql .= "DELETE FROM T99FAVORITE";
			$sql .= " WHERE T99_USER_CD = :user_cd ";
			$sql .= " AND (";

			for ($i=0; $i<count($strSeq_no); $i++)
			{
				$opt = " OR ";
				if ($i == 0) { $opt = "";}
				
				$sql .= $opt . " T99_HEYA_CD = :heya_cd_$i ";
				$db_params["heya_cd_$i"] = $strSeq_no[$i];
			}

			$sql .= " )";

			//=====データ登録=====
			$this->dbExecQuery($sql, $db_params, $db, "T99FAVORITE");

			$this->commitTransaction($db);
			$resCd = "0001";
		}
		catch (Exception $e)
		{
			$this->rollbackTransaction($db);
			$resCd = "9903";
		}
		$db->closeConnection();

		return $resCd;
    }

	/**
	 * お気に入り物件削除（非ログイン時）
	 * @param Array $strSeq_no 部屋CD
	 * @return
	 */
	public function deleteFavoriteBukkenCookie($strSeq_no)
	{
		// 外部モデル呼び出し設定
		$loader = new Zend_Application_Module_Autoloader(array(
			'namespace' => 'Rstdtl',
			'basePath' => APPLICATION_PATH . '/modules/rstdtl',
		));
		// モデル生成
		$model_dtlcookie = new Rstdtl_Model_Dtlcookie();

		try{
			// クッキー情報を取得
			if($_COOKIE[Apm_Config_Rstdtl::NAME_COOKIE_OKINIIRI_CNT] <> "") {
				$cookieArray = $model_dtlcookie->getCookieAll(Apm_Config_Rstdtl::NAME_COOKIE_OKINIIRI,$_COOKIE[Apm_Config_Rstdtl::NAME_COOKIE_OKINIIRI_CNT]);
				if(empty($cookieArray)){
					// キーで昇順ソート
					ksort($cookieArray);
				}

				// 保持期間設定
				$limit = time() + (Apm_Config_Rstdtl::DAY_KEEP_COOKIE * 24 * 3600);
				$tempArray = array();
				$cnt=0;
				foreach($cookieArray as $val)
				{
					// 削除物件でなければ、配列に追加
					if (!in_array($val,$strSeq_no)) {
						$cnt++;
						$tempArray[(int)($cnt / Apm_Config_Rstdtl::MAX_CNT_SUBKEY)][] = $val;
					}
				}
				// クッキー削除
				$model_dtlcookie->DeleteAllCookie(Apm_Config_Rstdtl::NAME_COOKIE_OKINIIRI,Apm_Config_Rstdtl::NAME_COOKIE_OKINIIRI_CNT);
				// Cookie再作成
				foreach ($tempArray as $key => $val) {
					foreach ($val as $final_key => $final_val ) {
						$tempStr .= "Bukken" .($final_key + 1). "=". $final_val ."&";
					}
					// 最後尾の & 削除
					$tempStr = mb_substr($tempStr, 0 ,mb_strlen($tempStr) -1 );
					
					// Cookie再作成
					setrawcookie(Apm_Config_Rstdtl::NAME_COOKIE_OKINIIRI.($key + 1), $tempStr, $limit, "/");
				}
				// 登録件数Cookie再作成
				if ($cnt > 0) {
					setcookie(Apm_Config_Rstdtl::NAME_COOKIE_OKINIIRI_CNT, $cnt, $limit, "/");
				}
			}
		}
		catch(Exception $e)
		{
			// エラーメッセージをログに書き出す
			__log_debug(__FILE__, __LINE__, __METHOD__, $e->getMessage());
			// クッキー削除
			$model_dtlcookie->DeleteAllCookie(Apm_Config_Rstdtl::NAME_COOKIE_OKINIIRI,Apm_Config_Rstdtl::NAME_COOKIE_OKINIIRI_CNT);
		}
	}

}
?>
